<template>
  <div class="upload">
    <div class="TopTitle" slot="header">
      <div class="fl">
        <!-- <span @click="back">
          <i class="el-icon-arrow-left">返回</i>
        </span>-->
        <b>上传共享</b>
      </div>
      <div class="fr">
        <el-button
          type="primary"
          size="mini"
          style="background: #7f92f7; border-color: #7f92f7"
          @click="saveAction(0)"
          :loading="submitLoading"
          >保存</el-button
        >
        <el-button
          type="danger"
          size="mini"
          style="background: #7ed093; border-color: #7ed093"
          @click="saveAction(1)"
          >发布</el-button
        >
        <el-button
          type="primary"
          size="mini"
          style="background: #fff; border-color: #5b5b5b; color: #5b5b5b"
          @click="back"
          >返回</el-button
        >
      </div>
    </div>
    <div class="up-pic"></div>
    <div class="centerForm">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题：" prop="title">
          <el-input v-model="ruleForm.title" style="width: 400px"></el-input>
        </el-form-item>
        <el-form-item label="栏目：" required>
          <el-col :span="12">
            <el-form-item prop="typeId">
              <el-select
                v-model="ruleForm.typeId"
                placeholder="请选择所属栏目"
                style="width: 190px"
                @change="handleType(ruleForm.typeId, ruleForm.subTypeName)"
              >
                <el-option label="专题分析" value="1"></el-option>
                <el-option label="经营通报" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" prop="subTypeName">
            <el-form-item
              label="子栏目:"
              label-width="50px"
              style="position: relative"
            >
              <!-- <el-autocomplete
                :fetch-suggestions="querySearch"
                v-model="ruleForm.subTypeName"
                :maxlength="8"
                style="width: 140px; margin-left: 10px"
                @keyup.native="handleSubType(ruleForm.subTypeName)"
              ></el-autocomplete> -->
              <el-input
                v-model="ruleForm.subTypeName"
                :maxlength="8"
                style="width: 140px; margin-left: 10px"
                @focus.stop="showTips = true"
                @blur="selectTipsBlur()"
                @keyup.native="handleSubType(ruleForm.subTypeName)"
              ></el-input>
              <ul class="tips" v-if="showTips">
                <li
                  v-for="(it, index) in suggestion"
                  :key="index"
                  @click="selectTips(it)"
                >
                  {{ it.value }}
                </li>
              </ul>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="时间：" required>
          <el-col :span="12">
            <el-form-item prop="fileYear">
              <el-date-picker
                style="width: 190px"
                v-model="ruleForm.fileYear"
                format="yyyy"
                type="year"
                value-format="yyyy"
                placeholder="选择年份"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="fileMonth">
              <el-select
                style="width: 190px; margin-left: 10px"
                v-model="ruleForm.fileMonth"
                class="fileYear"
              >
                <el-option
                  v-for="item in monthOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="可见范围：" prop="areaIdStr">
          <el-input
            :readonly="true"
            style="width: 400px"
            v-model="areaIdStrName1"
            placeholder="请选择可见范围"
            @click.native="selectArea"
          ></el-input>
          <!-- <el-button
            @click="selectArea"
            size="mini"
            style="background: #7f92f7; border-color: #7f92f7;"
            type="primary"
          >选择</el-button>-->
        </el-form-item>
        <el-form-item label="文章简介：" prop="descript">
          <el-input
            type="textarea"
            v-model="ruleForm.descript"
            style="width: 400px"
            resize="none"
            :autosize="{ minRows: 4, maxRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传附件：" prop="files">
          <el-upload
            style="width: 300px"
            class="upload-demo"
            ref="upload"
            multiple
            action="/api/releaseSecond/saveCatalogFiles"
            :on-change="handleChange"
            :file-list="ruleForm.files"
            :auto-upload="false"
            accept="image/*, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .txt, word, excel, pdf, txt, ppt"
          >
            <el-button
              slot="trigger"
              style="background: #7f92f7; border-color: #7f92f7"
              size="small"
              type="primary"
              >添加附件</el-button
            >
            <div slot="tip" class="el-upload__tip" style="color: red">
              文件大小不能超过50M
            </div>
          </el-upload>
          <ul>
            <li class="selfLi" v-for="item in attachFiles" :key="item.fildId">
              <i
                class="el-icon-document"
                style="margin-right: 7px; color: #909399"
              ></i>
              <span>{{ item.attachName }}</span>
              <i class="el-icon-close" @click="deteteList(item.attachId)"></i>
            </li>
          </ul>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :visible.sync="showSelectArea"
      width="30%"
      class="selectArea"
      @close="getSelect"
    >
      <div slot="title">选择可见范围</div>
      <div>
        <el-tree
          ref="tree"
          node-key="areaId"
          :default-expanded-keys="expandedKey"
          :data="treeData"
          :props="defaultProps"
          show-checkbox
        ></el-tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSelectArea = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="getCheckNode" size="mini"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog :visible.sync="showInfo" width="30%" class="selectArea">
      <div slot="title">提示</div>
      <div class="content">
        <img :src="(type = 'save' ? saveImage : releaseImage)" />
        <p>
          {{
            (type = "save"
              ? "已保存！下次进入可继续修改、发布"
              : "文章发布成功！")
          }}
        </p>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { $budgetAPI } from "@/api";
import { _debounce } from "@/utils/common.js";
import { relativeTimeThreshold } from "moment";
export default {
  name: "uploadShare",
  data() {
    var validFiles = (rule, value, callback) => {
      if (value.length == 0 && this.attachFiles.length == 0) {
        callback(new Error("请上传附件"));
      } else {
        callback();
      }
    };
    return {
      areaIdStrName: [],
      monthOptions: [
        {
          value: "01",
          label: "1月",
        },
        {
          value: "02",
          label: "2月",
        },
        {
          value: "03",
          label: "3月",
        },
        {
          value: "04",
          label: "4月",
        },
        {
          value: "05",
          label: "5月",
        },
        {
          value: "06",
          label: "6月",
        },
        {
          value: "07",
          label: "7月",
        },
        {
          value: "08",
          label: "8月",
        },
        {
          value: "09",
          label: "9月",
        },
        {
          value: "10",
          label: "10月",
        },
        {
          value: "11",
          label: "11月",
        },
        {
          value: "12",
          label: "12月",
        },
      ],
      showInfo: false,
      type: 1, //1专题分析，2是经营通报
      ruleForm: {
        files: [],
        title: "",
        descript: "",
        typeId: null,
        areaIdStr: [],
        fileYear: new Date().getFullYear().toString(),
        fileMonth: "",
        subTypeName: "",
      },
      attachFiles: [],
      rules: {
        title: [
          { required: true, message: "请输入标题名称", trigger: "blur" },
          { min: 4, message: "长度在不可小于4个字符", trigger: "blur" },
        ],
        fileYear: [
          {
            type: "string",
            // type: "date",
            required: false,
            message: "请选择年份",
            trigger: "change",
          },
        ],
        fileMonth: [
          {
            required: true,
            message: "请选择月份",
            trigger: "change",
          },
        ],
        descript: [
          { required: false, message: "请输入文章简介", trigger: "blur" },
        ],
        files: [{ required: true, validator: validFiles, trigger: "blur" }],
        areaIdStr: [
          { required: true, message: "请选择可见范围", trigger: "blur" },
        ],
        typeId: [
          { required: true, message: "请选择所属栏目", trigger: "change" },
        ],
        subTypeName: [
          { required: false, message: "请输入子栏目", trigger: "blur" },
        ],
      },
      saveImage: require("@/assets/images/common/sharingD.png"),
      releaseImage: require("@/assets/images/common/sharingS.png"),
      treeData: [],
      expandedKey: [], //默认展开的id集合
      defaultProps: {
        children: "childrenList",
        label: "logName",
      },
      submitLoading: false,
      showSelectArea: false, //控制可见范围弹窗的显示
      suggestion: [],
      showTips: false,
    };
  },
  computed: {
    areaIdStrName1() {
      return this.areaIdStrName.join(",");
    },
  },
  methods: {
    getSelect() {
      this.$refs.tree.setCheckedNodes([]);
    },
    getTree() {
      const that = this;
      $budgetAPI.getDetailAreaTree(
        {},
        (res) => {
          this.alertError(res);
          if (res.code == 0) {
            this.treeData = res.content;
            this.setName(res.content);
            this.treeData.forEach(function (item) {
              that.expandedKey.push(item.areaId);
            });
          }
        },
        (err) => {}
      );
    },
    getCheckNode() {
      const that = this;
      this.areaIdStrName = [];
      this.showSelectArea = false;
      const idStr = this.$refs.tree.getCheckedKeys();
      this.ruleForm.areaIdStr = idStr;
      const nodes = this.$refs.tree.getCheckedNodes();
      nodes.forEach(function (item) {
        if (
          idStr.includes(item.areaId) &&
          !that.areaIdStrName.includes(item.logName)
        ) {
          that.areaIdStrName.push(item.logName);
        }
      });
      // console.log(this.$refs.tree.getCheckedNodes())
    },
    selectArea() {
      this.showSelectArea = true;
      const that = this;
      setTimeout(function () {
        that.$refs.tree.setCheckedKeys(that.ruleForm.areaIdStr);
      }, 100);
    },
    saveAction(isRelease) {
      const that = this;
      this.submitLoading = true;
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          let formData = new FormData();
          Object.keys(this.ruleForm).forEach(function (key) {
            if (key != "files") {
              console.log(key, that.ruleForm[key]);
              formData.append(key, that.ruleForm[key]);
            } else {
              that.ruleForm.files.forEach(function (item, index) {
                formData.append(`files`, item.raw);
              });
            }
          });
          //编辑的时候才有id才需要添加
          if (this.$route.params.seq) {
            let arr = [];
            for (let i = 0; i < this.attachFiles.length; i++) {
              const item = this.attachFiles[i];
              arr.push(item.attachId);
            }
            formData.append(`attachIdStr`, arr);
            formData.append(`fileId`, this.$route.params.seq);
          }
          formData.append(`isRelease`, isRelease);
          //budgetShareAdd   updateFilesInfo
          const type = that.$route.params.seq
            ? "updateFilesInfo"
            : "budgetShareAdd";
          $budgetAPI[type](
            formData,
            (res) => {
              this.alertError(res);
              if (res.code == 0) {
                this.type = "save";
                this.showInfo = true;
                let timer = null;
                timer = setTimeout(function () {
                  clearTimeout(timer);
                  timer = null;
                  that.$router.go(-1);
                }, 1000);
              }
              this.submitLoading = false;
            },
            (err) => {
              this.submitLoading = false;
            }
          );
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    handleChange(file, fileList) {
      this.ruleForm.files = fileList;
    },
    back() {
      this.$router.go(-1);
    },
    deteteList(id) {
      const that = this;
      // console.log(this.attachFiles,id,'sdadada')
      let arr = this.attachFiles.filter((item) => {
        return item.attachId != id;
      });
      this.attachFiles = arr;
    },
    setName(datas) {
      //遍历树  获取id数组
      for (var i in datas) {
        const yes =
          this.ruleForm.areaIdStr.includes(datas[i].areaId) &&
          !this.areaIdStrName.includes(datas[i].logName);
        if (yes) {
          this.areaIdStrName.push(datas[i].logName);
        }
        if (datas[i].childrenList) {
          return this.setName(datas[i].childrenList);
        }
      }
    },
    getData() {
      $budgetAPI.budgetShareDetail(
        { fileId: this.$route.params.seq },
        (res) => {
          this.alertError(res);
          if (res.code == 0) {
            const that = this;
            const ruleInfo = res.content.fileInfo;
            this.attachFiles = res.content.attachFiles;
            this.ruleForm.areaIdStr = res.content.areaIds;
            ruleInfo.descript = ruleInfo.descript || "";

            Object.keys(ruleInfo).forEach(function (key) {
              if (that.ruleForm.hasOwnProperty(key)) {
                console.log(key);
                that.ruleForm[key] = ruleInfo[key];
              }
            });
            this.handleType(ruleInfo.typeId, ruleInfo.subTypeName);
          }
        },
        (err) => {}
      );
    },
    handleType(val, subVal) {
      var that = this,
        s = [];

      that.suggestion = [];

      // if(!subVal && that.count > 0) {
      //   return;
      // }
      // that.count++;
      that.ruleForm.subTypeName = subVal + "";
      $budgetAPI.getSubTypeList(
        {
          typeId: val,
          subTypeName: that.ruleForm.subTypeName,
        },
        (res) => {
          console.log(res);
          res.content.map((it) => {
            var obj = {
              value: it,
            };
            s.push(obj);
            // setTimeout(function () {
            that.suggestion = s;
            // }, 3000);
            // that.$nextTick(() => {});
          });
        },
        (err) => {
          console.log(err);
        }
      );
    },
    handleSubType: _debounce(function (val) {
      this.ruleForm.typeId && this.handleType(this.ruleForm.typeId, val || "");
    }, 500),
    // handleSubType(val) {
    //   this.ruleForm.typeId && this.handleType(this.ruleForm.typeId, val);
    // },
    querySearch(queryString, cb) {
      let suggestion = this.suggestion;
      // var results = queryString
      //   ? suggestion.filter(this.createStateFilter(queryString))
      //   : suggestion;
      // clearTimeout(this.timeout);
      //  this.timeout = setTimeout(() => {
      //     cb(suggestion);
      //   }, 0 );
      cb(suggestion);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    selectTips(it) {
      var that = this;
      that.ruleForm.subTypeName = it.value;

      that.showTips = false;
    },
    selectTipsBlur() {
      var that = this;
      setTimeout(function () {
        that.showTips = false;
      }, 300);
    },
  },
  created() {
    let that = this;
    if (this.$route.params.seq) {
      this.getData();
    } else {
      let m = new Date().getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      //  that.ruleForm.fileYear = (new Date()).getFullYear();
      that.ruleForm.fileMonth = m;
      //  that.ruleForm.fileYear = new Date();
    }
  },
  mounted() {
    this.getTree();
  },
};
</script>
<style lang="scss" scoped>
.centerForm {
  display: flex;
  align-items: center;
  justify-content: space-around;
  /deep/ .el-input__inner {
    height: 38px;
    line-height: 38px;
    border-radius: 0;
    border: 1px solid #cdcfd9; /*#9799a5*/
    font-size: 12px;
    color: #333;
  }
  /deep/ .el-form-item__label {
    font-size: 12px;
    padding: 0;
  }
}
.up-pic {
  width: 100%;
  height: 28px;
  margin: 75px auto 20px;
  background: url("~@/assets/images/common/upload-title.png") 53% 50% no-repeat;
  background-size: contain;
}
.TopTitle {
  padding: 10px 18px 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #636d9a;
  border-bottom: 1px solid #eaeaea;
  .fl {
    > span {
      font-weight: bold;
      cursor: pointer;
    }
    > b {
      color: #7f92f7;
      font-weight: bolder;
      font-size: 15px;
    }
  }
}
.selectArea {
  overflow: hidden;
  /deep/ > .el-dialog > .el-dialog__body {
    padding: 0 20px;
  }
  /deep/ > .el-dialog > .el-dialog__header {
    background: #5f6581;
    color: white;
    line-height: 50px;
  }
  /deep/ > .el-dialog > .el-dialog__body {
    height: 420px;
    overflow-y: auto;
  }
  .content {
    padding: 20px 0 35px 0;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    > img {
      width: 140px;
      height: 120px;
    }
  }
}
.el-icon-close {
  display: none;
}
.selfLi {
  padding-left: 4px;
  width: 300px;
  position: relative;
  display: flex;
  align-items: center;
  > span {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: block;
    width: 240px;
  }
}
.selfLi:hover > .el-icon-close {
  display: block;
  position: absolute;
  right: 6px;
  top: 13px;
  cursor: pointer;
  color: #606266;
}
.tips {
  position: absolute;
  top: 40px;
  left: 10px;
  z-index: 2;
  margin: 5px 0;
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background-color: #fff;
  li {
    width: 140px;
    cursor: poniter;
    padding: 0 20px;
    margin: 0;
    line-height: 34px;
    cursor: pointer;
    color: #606266;
    font-size: 14px;
    list-style: none;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
